package org.tc.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tc.bean.User;
import org.tc.exception.CustomException;
import org.tc.mapper.UserMapper;
import org.tc.service.JedisService;
import org.tc.service.UserService;
import org.tc.utils.JsonUtils;

import java.util.Date;
import java.util.UUID;

/**
 * Created by zxd on 2018/1/31.
 */
@Service
public class UserServiceImpl implements UserService{

    private Logger LOGGER= LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private JedisService jedisService;

    public final String USER_LOGIN="user_login:";

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) throws CustomException {
        if(user==null){
            return;
        }
        //1.用户名和电话不能重复
        if(queryByPhone(user.getPhone())!=null){
            LOGGER.info("电话号码已经被注册了 电话号码是{}",user.getPhone());
            throw  new CustomException("电话号码已经被注册了!");
        }
        if(queryByUsername(user.getUsername())!=null){
            LOGGER.debug("用户名已经被注册!{}",user.getUsername());
            throw  new CustomException("用户名已经被注册了!");
        }
        //2.加密
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        user.setCreated(new Date());
        user.setUpdated(user.getCreated());
        //3.保存
        userMapper.insertSelective(user);
    }

    public User queryByPhone(String phone){
        User record=new User();
        record.setPhone(phone);
        return userMapper.selectOne(record);
    }

    public User queryByUsername(String username){
        User record=new User();
        record.setUsername(username);
        return userMapper.selectOne(record);
    }



    @Override
    public String login(String username, String password) throws CustomException {
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            LOGGER.debug("参数为空!");
            return null;
        }
        //密码加密，根据用户名和密码查找用户
        User record=new User();
        record.setUsername(username);
        record.setPassword(DigestUtils.md5Hex(password));
        User user = userMapper.selectOne(record);
        if(user==null){
            //用户名密码错误
            LOGGER.debug("用户{}，用户名密码错误",username);
            throw new CustomException("用户名密码错误");
        }
        //处理登录
        String token=UUID.randomUUID().toString();
        //设置登录信息到redis服务器
        jedisService.set(USER_LOGIN+token,JsonUtils.objectToJson(user));
        LOGGER.info("用户{},登录的token为{}",username,token);
        //设置过期时间
        jedisService.expire(USER_LOGIN+token,60*60*2);
        return token;
    }

    @Override
    public User queryUserByToken(String token) {
        LOGGER.info("当前查询的用户的token为{}",token);
        String json=jedisService.get(USER_LOGIN+token);
        if(StringUtils.isEmpty(json)){
            LOGGER.info("登录时效,token 为{}",token);
            return null;
        }
        //重置登录时效时间
        jedisService.expire(USER_LOGIN+token,60*60*2);
        return JsonUtils.jsonToPojo(json,User.class);
    }


    @Override
    public String loginByPhone(String phoneNumber, String smscode) throws CustomException {
        //1.获取验证码
        //2.比较验证码
        //3.登录
        String service_code=jedisService.get("login_sms:"+phoneNumber);
        if(StringUtils.isEmpty(service_code)){
            throw  new CustomException("验证码失效!");
        }
        if(!smscode.equals(service_code)){
            throw  new CustomException("验证码输入错误!");
        }
        User record=new User();
        record.setPhone(phoneNumber);
        User user = userMapper.selectOne(record);
        if(user==null){
            //用户名密码错误
            LOGGER.debug("手机号{}用户，用户没有注册",phoneNumber);
            throw new CustomException("用户没有注册");
        }
        //处理登录
        String token=UUID.randomUUID().toString();
        //设置登录信息到redis服务器
        jedisService.set(USER_LOGIN+token,JsonUtils.objectToJson(user));
        LOGGER.info("用户{},登录的token为{}",phoneNumber,token);
        //设置过期时间
        jedisService.expire(USER_LOGIN+token,60*60*2);
        return token;
    }

    @Override
    public Boolean check(String param, Integer type) {
        if (type < 1 || type > 3) {
            return null;
        }
        User record = new User();
        switch (type) {
            case 1:
                record.setUsername(param);
                break;
            case 2:
                record.setPhone(param);
                break;
            case 3:
                record.setEmail(param);
                break;
            default:
                break;
        }
        return this.userMapper.selectOne(record)!=null;
    }



}
